package com.yuji.aacar.controller.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseActivity;
import com.yuji.aacar.base.Const;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.base.UserCenter;
import com.yuji.aacar.bean.beans.Order;
import com.yuji.aacar.bean.beans.QueryCarAddressInfo;
import com.yuji.aacar.bean.beans.Room;
import com.yuji.aacar.bean.beans.Serial;
import com.yuji.aacar.bean.request.SubmitRequest;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.bean.response.OrderDetailResponse;
import com.yuji.aacar.bean.response.OrderSelectResponse;
import com.yuji.aacar.bean.response.SubmitResponse;
import com.yuji.aacar.controller.address.AddressActivity;
import com.yuji.aacar.controller.address.roomaddress.RoomAddressActivity;
import com.yuji.aacar.controller.mine.carmanage.CarManagementActivity;
import com.yuji.aacar.controller.order.coupon.CouponActivity;
import com.yuji.aacar.controller.order.picker.TimeBean;
import com.yuji.aacar.controller.others.EditContentActivity;
import com.yuji.aacar.controller.recharge.RechargeActivity;
import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.fres.CoreImageLoader;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.utils.TimeUtils;
import com.yuji.aacar.widgets.autolayout.AutoLinearLayout;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.pickview.model.IPickerViewData;
import com.yuji.aacar.widgets.popwindow.PopItemAction;
import com.yuji.aacar.widgets.popwindow.PopWindow;
import com.yuji.aacar.widgets.textview.PingFangTextView;
import com.yuji.aacar.widgets.wheel.FromToTimePicker;
import com.yuji.aacar.wxapi.WXPayEntryActivity;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yuji.aacar.R.id.write_order_contact_province_tv;

public class WriteOrderActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.back_image)
    AutoRelativeLayout backImage;
    @BindView(R.id.title_content)
    PingFangTextView titleContent;
    @BindView(R.id.back_login)
    PingFangTextView backLogin;
    @BindView(R.id.title_message_iv)
    ImageView titleMessageIv;
    @BindView(R.id.title_message_rl)
    AutoRelativeLayout titleMessageRl;
    @BindView(R.id.title_rl)
    AutoRelativeLayout titleRl;
    @BindView(R.id.write_order_top_layout)
    AutoLinearLayout writeOrderTopLayout;
    @BindView(R.id.write_order_submit)
    TextView writeOrderSubmit;
    @BindView(R.id.write_order_submit_account)
    TextView writeOrderSubmitAccount;
    @BindView(R.id.write_order_bottom_layout)
    AutoRelativeLayout writeOrderBottomLayout;
    @BindView(R.id.write_order_product_icon_iv)
    ImageView writeOrderProductIconIv;
    @BindView(R.id.write_order_product_title_tv)
    PingFangTextView writeOrderProductTitleTv;
    @BindView(R.id.write_order_product_price_tv)
    TextView writeOrderProductPriceTv;
    @BindView(R.id.write_order_product_detail_tv)
    PingFangTextView writeOrderProductDetailTv;
    @BindView(R.id.write_order_become_number_price_tv)
    TextView writeOrderBecomeNumberPriceTv;
    @BindView(R.id.write_order_become_number_tv)
    TextView writeOrderBecomeNumberTv;
    @BindView(R.id.write_order_choose_car_rlayout)
    AutoRelativeLayout writeOrderChooseCarRlayout;
    @BindView(R.id.write_order_contact_rlayout)
    AutoRelativeLayout writeOrderContactRlayout;
    @BindView(R.id.write_order_contact_phone_tv)
    PingFangTextView writeOrderContactPhoneTv;
    @BindView(R.id.write_order_contact_phone_rlayout)
    AutoRelativeLayout writeOrderContactPhoneRlayout;
    @BindView(write_order_contact_province_tv)
    PingFangTextView writeOrderContactProvinceTv;
    @BindView(R.id.write_order_contact_province_rlayout)
    AutoRelativeLayout writeOrderContactProvinceRlayout;
    @BindView(R.id.write_order_contact_address_tv)
    PingFangTextView writeOrderContactAddressTv;
    @BindView(R.id.write_order_contact_address_rlayout)
    AutoRelativeLayout writeOrderContactAddressRlayout;
    @BindView(R.id.write_order_servetime_tv)
    PingFangTextView writeOrderServetimeTv;
    @BindView(R.id.write_order_servetime_rlayout)
    AutoRelativeLayout writeOrderServetimeRlayout;
    @BindView(R.id.write_order_youhuima_tv)
    PingFangTextView writeOrderYouhuimaTv;
    @BindView(R.id.write_order_youhuima_rlayout)
    AutoRelativeLayout writeOrderYouhuimaRlayout;
    @BindView(R.id.write_order_jifen_tv)
    PingFangTextView writeOrderJifenTv;
    @BindView(R.id.write_order_jifen_rlayout)
    AutoRelativeLayout writeOrderJifenRlayout;
    @BindView(R.id.write_order_total_account_tv)
    PingFangTextView writeOrderTotalAccountTv;
    @BindView(R.id.write_order_total_account_rlayout)
    AutoRelativeLayout writeOrderTotalAccountRlayout;
    @BindView(R.id.write_order_total_youhuiquan_tv)
    PingFangTextView writeOrderTotalYouhuiquanTv;
    @BindView(R.id.write_order_total_youhuiquan_rlayout)
    AutoRelativeLayout writeOrderTotalYouhuiquanRlayout;
    @BindView(R.id.write_order_total_jifen_tv)
    PingFangTextView writeOrderTotalJifenTv;
    @BindView(R.id.write_order_total_jifen_rlayout)
    AutoRelativeLayout writeOrderTotalJifenRlayout;
    @BindView(R.id.write_order_car_iv)
    SimpleDraweeView writeOrderCarIv;
    @BindView(R.id.write_order_name)
    PingFangTextView writeOrderName;
    @BindView(R.id.write_order_car_tv)
    PingFangTextView writeOrderCarTv;
    @BindView(R.id.write_order_carno_tv)
    PingFangTextView writeOrderCarnoTv;
    @BindView(R.id.write_order_contact_carno_rlayout)
    AutoRelativeLayout writeOrderContactCarnoRlayout;
    @BindView(R.id.write_order_product_price_9_llayout)
    AutoLinearLayout writeOrderProductPrice9Llayout;
    @BindView(R.id.write_order_product_price_rmb)
    PingFangTextView writeOrderProductPriceRmb;
    @BindView(R.id.write_order_product_price_9_money)
    PingFangTextView writeOrderProductPrice9Money;
    @BindView(R.id.write_order_product_price_9_right)
    AutoLinearLayout writeOrderProductPrice9Right;


    private WriteOrderActivityVM writeOrderActivityVM;
    private View customView;
    private FromToTimePicker fromToTimePicker;
    private PopWindow.Builder popWindow;


    private int washType = 0; // 1-预约洗车 2-及时洗车
    private String startTime;
    private String toTime;
    private String finalBookStartTime;
    private String finalBookendTime;
    private String finalNYR;
    private String finalTimeStr;
    private boolean isToday;

    private ArrayList<TimeBean> options1Items = new ArrayList<>();//一行
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<IPickerViewData>>> options3Items = new ArrayList<>();



    private Serial carCache; //车系
    private Room roomCache; //单独选择
    private OrderSelectResponse selectResponse;
    private QueryCarAddressInfo defaultAddress;
    private OrderDetailResponse buyAgainOrderDetails;//再次购买刷出来的数据


    private String productPriceStr;//产品金额
    private float productPrice;//产品金额

    private String rankPriceStr;//会员价格
    private float rankPrice;//会员价格

    private String name;
    private String phoneNo;
    private String addressDetail;
    private String address;
    private String carNo;
    private String serveTime;

    private Order orderTemp;
    private String userId;
    private LoginResponse user;

    private String couponNo;
    private String couponAmountStr;//优惠券金额
    private float couponAmount;//优惠券金额


    private String jifenStr;//积分金额
    private float jifen;//积分金额

    private String productFinalPriceStr; //返回需要支付的金额
    private float productFinalPrice; //返回需要支付的金额


    private float finalPrice = 0;



    private int orderType; //再次购买 1

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_write_order);
        ButterKnife.bind(this);
        initTitle(true, "填写订单", null);
        //        initPicker();
        washType = getIntent().getIntExtra("washType", 0);
        orderType = getIntent().getIntExtra("orderType", 0);
        super.onCreate(savedInstanceState);

//        if (orderType == Const.ORDER_BUY_AGAIN) {//再来一单
//
//        } else {
            user = UserCenter.getCurrentUser();
            if (null != user) {
                userId = user.getMemberId();
                carCache = UserCenter.getFirstCar(userId);
                defaultAddress = UserCenter.getDefaultAddress(userId);
                orderTemp = UserCenter.getOrderHistory(userId);


               LogUtil.e("--onCreate--carCache--", carCache);
               LogUtil.e("--onCreate--defaultAddress--", defaultAddress);
               LogUtil.e("--onCreate--orderTemp--", orderTemp);

                if (null != orderTemp) {
                    if (null != defaultAddress){
                        writeOrderContactAddressTv.setText(defaultAddress.getDetailAddress());
                        writeOrderName.setText(defaultAddress.getUserName());
                        writeOrderContactPhoneTv.setText(defaultAddress.getPhoneNo());
                        writeOrderContactProvinceTv.setText(defaultAddress.getCityName() + " " + defaultAddress.getAreaName() + " " + defaultAddress.getRoomName());
                        writeOrderCarnoTv.setText(orderTemp.getCarNo());
                    } else{
                        CoreImageLoader.loadImage(writeOrderCarIv, orderTemp.getBrandUrl());
                        writeOrderCarTv.setText(orderTemp.getBrandName() + " " + orderTemp.getSeriesName());

                        writeOrderContactAddressTv.setText(orderTemp.getDetailAddress());
                        writeOrderName.setText(orderTemp.getLinkman());
                        writeOrderContactPhoneTv.setText(orderTemp.getPhoneNo());
                        writeOrderContactProvinceTv.setText(orderTemp.getCityName() + " " + orderTemp.getAreaName() + " " + orderTemp.getRoomName());
                        writeOrderCarnoTv.setText(orderTemp.getCarNo());

                        if (null == defaultAddress) {
                            defaultAddress = new QueryCarAddressInfo();
                            defaultAddress.setProvinceCode(orderTemp.getProvinceCode());
                            defaultAddress.setProvinceName(orderTemp.getProvinceName());
                            defaultAddress.setCityCode(orderTemp.getCityCode());
                            defaultAddress.setCityName(orderTemp.getCityName());
                            defaultAddress.setAreaCode(orderTemp.getAreaCode());
                            defaultAddress.setAreaName(orderTemp.getAreaName());
                            defaultAddress.setRoomCode(orderTemp.getRoomCode());
                            defaultAddress.setRoomName(orderTemp.getRoomName());
                        }
                    }

                    if (null != carCache) {
                        CoreImageLoader.loadImage(writeOrderCarIv, carCache.getBrandUrl());
                        writeOrderCarTv.setText(carCache.getBrandName() + " " + carCache.getSeriesName());
                    }
                } else {
                    if (null != defaultAddress){
                        writeOrderContactAddressTv.setText(defaultAddress.getDetailAddress());
                        writeOrderName.setText(defaultAddress.getUserName());
                        writeOrderContactPhoneTv.setText(defaultAddress.getPhoneNo());
                        writeOrderContactProvinceTv.setText(defaultAddress.getCityName() + " " + defaultAddress.getAreaName() + " " + defaultAddress.getRoomName());
                    } else {
                        writeOrderName.setText(user.getUserName());
                        writeOrderContactPhoneTv.setText(user.getPhoneNo());
                    }

                    if (null != carCache) {
                        CoreImageLoader.loadImage(writeOrderCarIv, carCache.getBrandUrl());
                        writeOrderCarTv.setText(carCache.getBrandName() + " " + carCache.getSeriesName());
                    }
                }

                if (orderType != Const.ORDER_BUY_AGAIN){
                    isNeedFirstJump();
                }
            }
//        }
        initPop();
    }

    @Override
    public void alreadyBindBaseViewModel() {
        super.alreadyBindBaseViewModel();
        writeOrderActivityVM = (WriteOrderActivityVM) coreBaseViewModel;

        if (orderType == Const.ORDER_BUY_AGAIN) {
            String orderNum = getIntent().getStringExtra("orderno");
            requestOrderDetail(orderNum);
        }

    }

    @Override
    public void onResume() {
        super.onResume();

        user = UserCenter.getCurrentUser();
        if (null != user) {
            userId = user.getMemberId();
            //            defaultAddress = UserCenter.getDefaultAddress(user.getMemberId());
            initWashTypeUI();
            if (orderType != Const.ORDER_BUY_AGAIN){
                requestPrice();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    public boolean isNeedFirstJump() {
        LogUtil.e("--isFirstJump--car ", carCache);
        LogUtil.e("--isFirstJump--orderTemp ", orderTemp);
        LogUtil.e("--isFirstJump--defaultAddress ", defaultAddress);

        if (null != carCache && null!= defaultAddress){
            UserCenter.setIsFirstUse(userId);
        } else {

            if (null != orderTemp){
                resetOrderTempUI();
               return false;
            } else {
                if (null != carCache) {
                    CoreImageLoader.loadImage(writeOrderCarIv, carCache.getBrandUrl());
                    writeOrderCarTv.setText(carCache.getBrandName() + " " + carCache.getSeriesName());

                } else {
                    showToast("您还没有选择您的车型！");
                    Intent intent = getIntent().putExtra("from", Const.FROM_WRITE_ORDER);
                    presentController(CarManagementActivity.class, intent);
                    return true;
                }
                if (null != defaultAddress) {
                    resetAddressUI(defaultAddress);
                } else {
                    showToast("您还没有选择您的小区！");
                    Intent intent = getIntent().putExtra("from", Const.FROM_WRITE_ORDER);
                    presentController(AddressActivity.class, intent);
                    return true;
                }
            }
        }

//        LogUtil.e("--isFirstJump--", roomCache);
//        if (null != roomCache) {
//            writeOrderContactProvinceTv.setText(roomCache.getCityName() + " " + roomCache.getAreaName() + " " + roomCache.getRoomName());
//        } else {
//            showToast("首次进入请选择您的小区！");
//            Intent intent2 = getIntent().putExtra("from", Const.FROM_WRITE_ORDER);
//            presentController(RoomAddressActivity.class, intent2);
//            return true;
//        }
        return false;
    }


    private void initPop() {
        customView = View.inflate(this, R.layout.layout_pop_view, null);
        PingFangTextView confirm = (PingFangTextView) customView.findViewById(R.id.pop_confirm);

        fromToTimePicker = (FromToTimePicker) customView.findViewById(R.id.timePicker);
        fromToTimePicker.setOnResultListener(new FromToTimePicker.OnResultListener() {
            @Override
            public void onConfirm(int fromHour, int fromMinute, int toHour, int toMinute) {
                LogUtil.e("onConfirm", "From " + fromHour + ":" + fromMinute + " To " + toHour + ":" + toMinute);


            }

            @Override
            public void onCancel() {
                //                textView.setText("Canceled");
            }
        });
        fromToTimePicker.setCurrentDate("", "");

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] back = fromToTimePicker.getFinalChooseDate();

                finalNYR = fromToTimePicker.getImmediateReserveNYR();
                finalTimeStr = back[0] + " " + back[2] + " ~ " + back[3];
                finalBookStartTime = finalNYR + " " + back[2] + ":00";
                finalBookendTime = finalNYR + " " + back[3] + ":00";
                LogUtil.e("--finalTimeStr--", finalNYR);
                LogUtil.e("--finalTimeStr--", finalBookStartTime);
                LogUtil.e("--finalTimeStr--", finalBookendTime);

                LogUtil.e("--finalTimeStr--", finalTimeStr);
                writeOrderServetimeTv.setText(finalTimeStr);
                popWindow.dismmiss();
                if (finalTimeStr.contentEquals("--")){
                    showToast("今天已经停止营业， 请选择明天时间！");
                } else {
                    requestPrice();
                }

            }
        });
    }

    private void initWashTypeUI() {

        if (user.getRankId().contentEquals("1")) {//普通用户
            writeOrderProductDetailTv.setText("购买银牌会员首单 ¥9.9, 并享受会员价格,预约洗车3小时以上，享5元优惠！");
            writeOrderProductDetailTv.setTextColor(Color.RED);
            writeOrderProductDetailTv.setSelected(true);
        } else if (user.getIsFirstOrder().contentEquals("1")) {
            writeOrderProductDetailTv.setText("银牌会员首单 ¥9.9");
            writeOrderProductDetailTv.setTextColor(Color.RED);
            writeOrderProductDetailTv.setSelected(true);
        } else {
            writeOrderProductDetailTv.setText("更多优惠活动和会员优质服务即将开放，敬请关注！");
            writeOrderProductDetailTv.setTextColor(Color.RED);
            writeOrderProductDetailTv.setSelected(true);
        }

        if (washType == Const.WASH_TYPE_IMMEDIATE) {
            writeOrderProductIconIv.setImageResource(R.mipmap.icon_immediate);
            writeOrderProductTitleTv.setText("即时洗车");
            fromToTimePicker.DELAY_HOUR = 2;
            writeOrderServetimeRlayout.setEnabled(false);
        } else if (washType == Const.WASH_TYPE_RESERVE){
            writeOrderProductIconIv.setImageResource(R.mipmap.icon_reserve);
            writeOrderProductTitleTv.setText("预约洗车");
            fromToTimePicker.DELAY_HOUR = 3;
        }

        startTime = fromToTimePicker.getImmediateReserveFromTime();
        toTime = fromToTimePicker.getImmediateReserveToTime(startTime);

        LogUtil.e("--finalTimeStr--", finalTimeStr);

        finalNYR = fromToTimePicker.getImmediateReserveNYR();
        String today = TimeUtils.getSystemWashDate(0);
        if (today.contentEquals(finalNYR)) {
            isToday = true;
            finalTimeStr = "今天 " + startTime + " ~ " + toTime;
        } else {
            finalTimeStr = "明天 " + startTime + " ~ " + toTime;
        }
        finalBookStartTime = finalNYR + " " + startTime + ":00";
        finalBookendTime = finalNYR + " " + toTime + ":00";
        LogUtil.e("--finalTimeStr--", finalNYR);
        LogUtil.e("--finalTimeStr--", finalBookStartTime);
        LogUtil.e("--finalTimeStr--", finalBookendTime);

        writeOrderServetimeTv.setText(finalTimeStr);

    }


    @OnClick({R.id.write_order_become_number_tv, R.id.write_order_contact_carno_rlayout, R.id.write_order_choose_car_rlayout, R.id.write_order_submit, R.id.write_order_submit_account, R.id.write_order_contact_rlayout, R.id.write_order_contact_phone_rlayout, R.id.write_order_contact_province_rlayout, R.id.write_order_contact_address_rlayout, R.id.write_order_servetime_rlayout, R.id.write_order_youhuima_rlayout, R.id.write_order_jifen_rlayout, R.id.write_order_total_account_rlayout, R.id.write_order_total_youhuiquan_rlayout, R.id.write_order_total_jifen_rlayout})
    public void onClick(View view) {
        Intent intent = getIntent().putExtra("from", Const.FROM_WRITE_ORDER);
        switch (view.getId()) {
            case R.id.write_order_choose_car_rlayout:
                presentController(CarManagementActivity.class, intent);
                break;
            case R.id.write_order_become_number_tv:
                presentController(RechargeActivity.class);
                break;
            case R.id.write_order_submit_account:
                break;
            //            case R.id.write_order_product_price_9_9_llayout:
            //                break;
            case R.id.write_order_contact_rlayout:
                name = writeOrderName.getText().toString();
                intent.putExtra("content", name);
                intent.putExtra("from", Const.FROM_PERSONAL_INFO);
                intent.putExtra("type", "name");
                presentController(EditContentActivity.class, intent);
                break;
            case R.id.write_order_contact_phone_rlayout:
                phoneNo = writeOrderContactPhoneTv.getText().toString();
                intent.putExtra("content", phoneNo);
                intent.putExtra("type", "phone");
                presentController(EditContentActivity.class, intent);
                break;
            case R.id.write_order_contact_province_rlayout:
                presentController(RoomAddressActivity.class, intent);
                break;
            case R.id.write_order_contact_address_rlayout:
                addressDetail = writeOrderContactAddressTv.getText().toString();
                intent.putExtra("content", addressDetail);
                intent.putExtra("type", "address");
                presentController(EditContentActivity.class, intent);
                break;
            case R.id.write_order_contact_carno_rlayout:
                carNo = writeOrderCarnoTv.getText().toString();
                intent.putExtra("content", carNo);
                intent.putExtra("type", "carno");
                presentController(EditContentActivity.class, intent);
                break;
            case R.id.write_order_servetime_rlayout:
                //                pvTime.show();
                showPopWindow();
                break;
            case R.id.write_order_youhuima_rlayout:
                presentController(CouponActivity.class);
                break;
            case R.id.write_order_jifen_rlayout:
                break;
            case R.id.write_order_total_account_rlayout:
                break;
            case R.id.write_order_total_youhuiquan_rlayout:
                break;
            case R.id.write_order_total_jifen_rlayout:
                break;
            case R.id.write_order_submit:

                if (islegal()) {
                    writeOrderSubmit.setEnabled(false);
                    if (null == orderTemp){
                        orderTemp = new Order();
                    }

                    orderTemp.setWashType(washType + "");

                    orderTemp.setBrandId(carCache.getBrandId());
                    orderTemp.setBrandName(carCache.getBrandName());
                    orderTemp.setSeriesId(carCache.getPid());
                    orderTemp.setSeriesName(carCache.getSeriesName());
                    orderTemp.setCarType(carCache.getCarType());
                    orderTemp.setCarLibType(carCache.getCarLibType());
                    orderTemp.setBrandUrl(carCache.getBrandUrl());

                    orderTemp.setProvinceCode(defaultAddress.getProvinceCode());
                    orderTemp.setProvinceName(defaultAddress.getProvinceName());
                    orderTemp.setCityCode(defaultAddress.getCityCode());
                    orderTemp.setCityName(defaultAddress.getCityName());
                    orderTemp.setAreaCode(defaultAddress.getAreaCode());
                    orderTemp.setAreaName(defaultAddress.getAreaName());
                    orderTemp.setRoomCode(defaultAddress.getRoomCode());
                    orderTemp.setRoomName(defaultAddress.getRoomName());


                    orderTemp.setDetailAddress(addressDetail);
                    orderTemp.setCarNo(carNo);
                    orderTemp.setPhoneNo(phoneNo);
                    orderTemp.setLinkman(name);
                    orderTemp.setBookStartTime(finalBookStartTime);
                    orderTemp.setBookEndTime(finalBookendTime);

                    orderTemp.setCouponNo(couponNo);
                    orderTemp.setCouponAmount(couponAmountStr);

                    orderTemp.setPayIntegral(jifen + "");
                    //                    orderTemp.setPayIntegral("0");

                    orderTemp.setProductId(selectResponse.getProductId());
                    orderTemp.setProductPrice(selectResponse.getProductPrice());
                    orderTemp.setUserRankPrice(selectResponse.getUserRankPrice());
                    orderTemp.setBookDiscPrice(selectResponse.getBookDiscPrice());
                    orderTemp.setEnjoyPrice(selectResponse.getEnjoyPrice());
                    orderTemp.setResultProductPrice(selectResponse.getResultProductPrice());

                    orderTemp.setUserRankId(selectResponse.getUserRankId());

                    orderTemp.setPayAmount(finalPrice + "");

                    SubmitRequest requeset = new SubmitRequest();
                    requeset.setOrder(orderTemp);
                    requestParams = BaseServiceParams.submit(requeset);
                    doTask(BaseServiceMediator.SUBMIT);

                    UserCenter.setOrderHistory(userId, orderTemp);
                }
                //                                presentController(PayTwoActivity.class);
                break;
        }
    }


    private boolean islegal() {

        address = writeOrderContactProvinceTv.getText().toString();
        serveTime = writeOrderServetimeTv.getText().toString();

        name = writeOrderName.getText().toString();
        phoneNo = writeOrderContactPhoneTv.getText().toString();
        addressDetail = writeOrderContactAddressTv.getText().toString();
        carNo = writeOrderCarnoTv.getText().toString();

        //        couponAmount = writeOrderYouhuimaTv.getText().toString();

        if (TextUtils.isEmpty(name)) {
            showToast("请填写联系人信息！");
            return false;
        } else if (TextUtils.isEmpty(phoneNo)) {
            showToast("请填写联系手机！");
            return false;
        } else if (TextUtils.isEmpty(addressDetail)) {
            showToast("请填写详细的车辆停放地址！");
            return false;
        } else if (TextUtils.isEmpty(address)) {
            showToast("请填写所在地区！");
            return false;
        } else if (TextUtils.isEmpty(carNo)) {
            showToast("请填写车牌号码！");
            return false;
        } else if (TextUtils.isEmpty(serveTime)) {
            showToast("请填写希望服务时间！");
            return false;
        } else if (null == selectResponse) {
            showToast("请检查车型和所在地区是否填写完成！");
        } else if (null == defaultAddress) {
            showToast("请重新选择您的所在地区！");
        } else if (washType == 0) {
            showToast("请重新选择洗车类型！");
        }
        return true;
    }

    private void showPopWindow() {
        if (null == popWindow) {
            popWindow = new PopWindow.Builder(this)
                    .setStyle(PopWindow.PopWindowStyle.PopUp)
                    .addItemAction(new PopItemAction("选项"))//注意这里setVIew的优先级最高，及只要执行了setView，其他添加的view都是无效的
                    .setView(customView);
            popWindow.show();
        } else {
            popWindow.show();
            fromToTimePicker.setDate();
        }


    }


    private void requestPrice() {

        if (null != carCache && null != defaultAddress) {
            requestParams = BaseServiceParams.select(carCache.getCarType(), carCache.getCarLibType(),
                    defaultAddress.getProvinceCode(), defaultAddress.getCityCode(),
                    defaultAddress.getAreaCode(), defaultAddress.getRoomCode(), finalBookStartTime, finalBookendTime);
            doTask(BaseServiceMediator.SELECT);
        }
    }

    private void requestOrderDetail(String orderNumber) {
        requestParams = BaseServiceParams.detail(orderNumber);
        doTask(BaseServiceMediator.DETAIL);
    }

    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (response.getRequestCode() == BaseServiceMediator.SUBMIT_CODE) {
            writeOrderSubmit.setEnabled(true);
            SubmitResponse submitResponse = (SubmitResponse) response.getResponse();
            String orderNumber = submitResponse.getOrderNo();
//            showToast(orderNumber);
            if (submitResponse.getPayFlag().contentEquals("success")) {//积分支付， 或者优惠券支付完毕
                //                presentController(PayActivity.class);
                //                presentController(WXPayEntryActivity.class);
                DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        CoreEventCenter.postMessage(EventConst.PAY_FINISH, "");
                        finish();
                    }
                };
                showAlertDialogue("支付完成", "我们会尽快联系您！", clickListener);

            } else {//需要支付
                Intent intent = new Intent();
                intent.putExtra("orderNumber", orderNumber);
                intent.putExtra("amount", finalPrice + "");
                //                presentController(PayActivity.class, intent);
                presentController(WXPayEntryActivity.class, intent);
            }
        } else if (response.getRequestCode() == BaseServiceMediator.SELECT_CODE) {
            selectResponse = (OrderSelectResponse) response.getResponse();
            resetPriceUI(selectResponse);
        } else if (response.getRequestCode() == BaseServiceMediator.DETAIL_CODE) {
            OrderDetailResponse historyOrder = (OrderDetailResponse) response.getResponse();
            if (null != historyOrder){
                if (null == orderTemp){
                    orderTemp = new Order();
                }
                OrderUtils.convertOrderFromOrderDetailResponse(orderTemp, historyOrder);
                resetOrderTempUI();
                if (null == carCache){
                    carCache = new Serial();
                    carCache.setCarType(orderTemp.getCarType());
                    carCache.setCarLibType(orderTemp.getCarLibType());
                }
                if (null == defaultAddress) {
                    defaultAddress = new QueryCarAddressInfo();
                    defaultAddress.setProvinceCode(orderTemp.getProvinceCode());
                    defaultAddress.setProvinceName(orderTemp.getProvinceName());
                    defaultAddress.setCityCode(orderTemp.getCityCode());
                    defaultAddress.setCityName(orderTemp.getCityName());
                    defaultAddress.setAreaCode(orderTemp.getAreaCode());
                    defaultAddress.setAreaName(orderTemp.getAreaName());
                    defaultAddress.setRoomCode(orderTemp.getRoomCode());
                    defaultAddress.setRoomName(orderTemp.getRoomName());
                }
                orderType = 0;
                requestPrice();
            }
        }
    }


    @Override
    public void requestFailed(CoreServiceResponse response) {
        super.requestFailed(response);
        writeOrderSubmit.setEnabled(true);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        writeOrderSubmit.setEnabled(true);
    }

    /**
     * 重置 订单价格
     *
     * @param selectResponse
     */
    private void resetPriceUI(OrderSelectResponse selectResponse) {


        String rank = selectResponse.getUserRankId();//用户等级 2-银牌会员
        //        selectResponse.getIntegral();//用户积分
        String isFirst = selectResponse.getIsFirstOrder();////是否是首次充值用户
        //        selectResponse.getBookDiscPrice();//预约优惠价格
        //        selectResponse.getEnjoyPrice();//尊享价格
        //        selectResponse.getProductId();////产品ID
        //        selectResponse.getProductPrice();//产品标准价
        //        selectResponse.getUserRankPrice();//用户等级价格
        //        selectResponse.getResultProductPrice(); ////最终产品价格


        productPriceStr = selectResponse.getProductPrice();//产品价格
        rankPriceStr = selectResponse.getUserRankPrice();//会员价格
        jifenStr = selectResponse.getIntegral();//积分
        productFinalPriceStr = selectResponse.getResultProductPrice();//最终价格（不包含积分和优惠券）


        if (null != productFinalPriceStr) {
            productFinalPrice = Float.parseFloat(productFinalPriceStr);
            productFinalPrice = (float) (Math.round(productFinalPrice * 100)) / 100;
        }

        if (null != productPriceStr) {
            productPrice = Float.parseFloat(productPriceStr);
            productPrice = (float) (Math.round(productPrice * 100)) / 100;
        }

        if (null != rankPriceStr) {
            rankPrice = Float.parseFloat(rankPriceStr);
            rankPrice = (float) (Math.round(rankPrice * 100)) / 100;
        }

        if (null != jifenStr) {
            //            writeOrderJifenTv.setText(jifenStr);//用户剩余积分
            jifen = Float.parseFloat(jifenStr);
            jifen = (float) (Math.round(jifen * 100)) / 100;
        }

        if (null != couponAmountStr) { //优惠券
            couponAmount = Float.parseFloat(couponAmountStr);
            couponAmount = (float) (Math.round(couponAmount * 100)) / 100;
        }


        float showjifen = 0;
        float showyouhuiquan = 0;


        float dikoujifen = 0;
        if ((int) (couponAmount * 100) >= (int) (productFinalPrice * 100)) {
            dikoujifen = 0;
        } else{

            if (couponAmount > 0){
                dikoujifen = productFinalPrice  - couponAmount;
            } else {
                if (jifen > productFinalPrice) {
                    dikoujifen = productFinalPrice;
                } else {
                    dikoujifen = jifen;
                }
            }

        }
            dikoujifen = (float) (Math.round(dikoujifen * 100)) / 100;

        if (jifen > dikoujifen){
            writeOrderTotalJifenTv.setText("-" + dikoujifen + "分");//积分抵扣
        } else {
            dikoujifen = jifen;
            writeOrderTotalJifenTv.setText("-" + dikoujifen + "分");//积分抵扣
        }





        if ((int) (couponAmount * 100) >= (int) (productFinalPrice * 100)) {
            finalPrice = (float) (Math.round(0 * 100)) / 100;
            couponAmount = productFinalPrice;
            jifen = (float) (Math.round(0 * 100)) / 100;
        } else {
            if (couponAmount > 0){
                jifen = dikoujifen;
                finalPrice = (float) (Math.round((productFinalPrice - jifen - couponAmount) * 100)) / 100;
            } else {
                if (jifen - productFinalPrice > 0) {
                    finalPrice = (float) (Math.round(0 * 100)) / 100;
                    jifen = productFinalPrice;
                } else {
                    finalPrice = (float) (Math.round((productFinalPrice - jifen - couponAmount) * 100)) / 100;
                }
            }

        }

        writeOrderProductPriceTv.setText(productPriceStr);
        writeOrderBecomeNumberPriceTv.setText("会员价¥" + rankPriceStr);
        writeOrderJifenTv.setText(jifenStr + "分"); //账户积分


        writeOrderSubmitAccount.setText(finalPrice + ""); //最终价格
        writeOrderTotalAccountTv.setText("¥" + productFinalPriceStr);//洗车金额
        writeOrderTotalYouhuiquanTv.setText("- ¥" + couponAmount);//优惠券抵扣




        if (Integer.parseInt(rank) >= 2) { //充值会员

            if (Integer.parseInt(isFirst) == 1) {//首单用户
                writeOrderProductPrice9Llayout.setVisibility(View.VISIBLE);

                writeOrderBecomeNumberPriceTv.setVisibility(View.INVISIBLE);
                writeOrderBecomeNumberTv.setVisibility(View.INVISIBLE);
                writeOrderProductPriceTv.setVisibility(View.INVISIBLE);
                writeOrderProductPriceRmb.setVisibility(View.INVISIBLE);
                writeOrderYouhuimaRlayout.setEnabled(false);
            } else { //会员价用户
                writeOrderProductPrice9Llayout.setVisibility(View.VISIBLE);

                writeOrderProductPrice9Money.setVisibility(View.VISIBLE);
                writeOrderProductPrice9Money.setText(productFinalPriceStr); //会员金额

                writeOrderBecomeNumberPriceTv.setVisibility(View.INVISIBLE);
                writeOrderBecomeNumberTv.setVisibility(View.INVISIBLE);
                writeOrderProductPriceTv.setVisibility(View.INVISIBLE);
                writeOrderProductPriceRmb.setVisibility(View.INVISIBLE);
                writeOrderYouhuimaRlayout.setEnabled(true);
            }
        } else {

            writeOrderProductPrice9Llayout.setVisibility(View.INVISIBLE);

            writeOrderBecomeNumberPriceTv.setVisibility(View.VISIBLE);
            writeOrderBecomeNumberTv.setVisibility(View.VISIBLE);
            writeOrderProductPriceTv.setVisibility(View.VISIBLE);
            writeOrderProductPriceRmb.setVisibility(View.VISIBLE);
            writeOrderYouhuimaRlayout.setEnabled(true);
        }

    }


    @Override
    public void handleMessage(CoreEventBusMessage message) {
        super.handleMessage(message);

        if (message.getMessageCode().contentEquals(String.valueOf(EventConst.FIRST_DEFAULT_SERIAL_FINISH))) {//首次选车型
            carCache = (Serial) message.getMessageObjects();
            LogUtil.e("--handleMessage--carCache", carCache);

            if (null != carCache) {
                CoreImageLoader.loadImage(writeOrderCarIv, carCache.getBrandUrl());
                writeOrderCarTv.setText(carCache.getBrandName() + " " + carCache.getSeriesName());
            }
            if (null == defaultAddress) {
                showToast("首次进入请选择您的基本信息！");
                presentController(AddressActivity.class,getIntent().putExtra("from", Const.FROM_WRITE_ORDER));
            }
        }  else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.SELECT_CAR_OVER))) {//选择车型列表
            carCache = (Serial) message.getMessageObjects();
            LogUtil.e("--handleMessage--carCache", carCache);
            if (null != carCache) {
                CoreImageLoader.loadImage(writeOrderCarIv, carCache.getBrandUrl());
                writeOrderCarTv.setText(carCache.getBrandName() + " " + carCache.getSeriesName());
            }
            if (null == defaultAddress) {
                showToast("首次进入请选择您的基本信息！");
                presentController(AddressActivity.class,getIntent().putExtra("from", Const.FROM_WRITE_ORDER));
            }
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.FIRST_DEFAULT_ADDRESS_FINISH))) {//首次添加地址

            defaultAddress = (QueryCarAddressInfo) message.getMessageObjects();
            LogUtil.e("--handleMessage--首次添加地址", defaultAddress);
            resetAddressUI(defaultAddress);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.SELECT_ROOM_OVER))) { //选择小区地址
            roomCache = (Room) message.getMessageObjects();
            LogUtil.e("--handleMessage--roomCache", roomCache);
            if (null != roomCache) {
                writeOrderContactProvinceTv.setText(roomCache.getCityName() + " " + roomCache.getAreaName() + " " + roomCache.getRoomName());
                if (null == defaultAddress){
                    defaultAddress = new QueryCarAddressInfo();

                }
                    defaultAddress.setAreaName(roomCache.getAreaName());
                    defaultAddress.setAreaCode(roomCache.getAreaCode());
                    defaultAddress.setCityCode(roomCache.getCityCode());
                    defaultAddress.setCityName(roomCache.getCityName());
                    defaultAddress.setProvinceCode(roomCache.getProvinceCode());
                    defaultAddress.setProvinceName(roomCache.getProvinceName());
                    defaultAddress.setRoomCode(roomCache.getRoomCode());
                    defaultAddress.setRoomName(roomCache.getRoomName());

            }
            LogUtil.e("--handleMessage--roomCache", defaultAddress);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.SELECT_ADDRESS_OVER))) {//选择地址列表数据
            defaultAddress = (QueryCarAddressInfo) message.getMessageObjects();
            resetAddressUI(defaultAddress);
        }  else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.CHANGE_NAME))) {
            name = message.getMessage();
            writeOrderName.setText(name);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.CHANGE_PHONE))) {
            phoneNo = message.getMessage();
            writeOrderContactPhoneTv.setText(phoneNo);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.CHANGE_CARNO))) {
            carNo = message.getMessage();
            writeOrderCarnoTv.setText(carNo);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.CHANGE_ADDRESS_DETAIL))) {
            addressDetail = message.getMessage();
            writeOrderContactAddressTv.setText(addressDetail);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.COUPON))) {
            String[] str = message.getMessage().split(":");
            couponNo = str[0];
            couponAmountStr = str[1];
            couponAmount = Float.parseFloat(couponAmountStr);
            couponAmount = (float) (Math.round(couponAmount * 100)) / 100;
            writeOrderYouhuimaTv.setText("¥" + couponAmount);
        }
    }

    private void resetAddressUI(QueryCarAddressInfo defaultAddress) {
        if (null != defaultAddress){
            writeOrderName.setText(defaultAddress.getUserName());
            writeOrderContactPhoneTv.setText(defaultAddress.getPhoneNo());
            writeOrderContactAddressTv.setText(defaultAddress.getDetailAddress());
            writeOrderContactProvinceTv.setText(defaultAddress.getCityName() + " " + defaultAddress.getAreaName() + " " + defaultAddress.getRoomName());

        }
    }

    private void resetOrderTempUI() {
        CoreImageLoader.loadImage(writeOrderCarIv, orderTemp.getBrandUrl());
        writeOrderCarTv.setText(orderTemp.getBrandName() + " " + orderTemp.getSeriesName());
        writeOrderName.setText(orderTemp.getLinkman());

        writeOrderContactPhoneTv.setText(orderTemp.getPhoneNo());
        writeOrderContactAddressTv.setText(orderTemp.getDetailAddress());
        writeOrderContactProvinceTv.setText(orderTemp.getCityName() + " " + orderTemp.getAreaName() + " " + orderTemp.getRoomName());
        writeOrderCarnoTv.setText(orderTemp.getCarNo());
    }
}